package com.vhall.component.init;

import cn.hutool.core.collection.CollectionUtil;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.vhall.component.dao.room.RoomConfigMapper;
import com.vhall.component.dao.room.RoomMapper;
import com.vhall.component.entity.room.RoomConfig;
import com.vhall.component.entity.room.entity.RoomsEntity;
import com.vhall.component.plugin.common.constant.RedisKey;
import com.vhall.component.plugin.common.enums.RoomConfigStatusEnum;
import com.vhall.component.service.upload.UploadService;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.io.IOUtils;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.boot.ApplicationArguments;
import org.springframework.boot.ApplicationRunner;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.mock.web.MockMultipartFile;
import org.springframework.stereotype.Component;
import org.springframework.util.ResourceUtils;
import org.springframework.web.multipart.MultipartFile;

import javax.annotation.Resource;
import java.awt.image.BufferedImage;
import java.io.*;
import java.text.MessageFormat;
import java.time.LocalDateTime;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;
import java.util.concurrent.TimeUnit;
import java.util.stream.Collectors;

import static com.vhall.component.plugin.common.constant.RedisKey.RESOURCE_IMAGE_GX;

/**
 * @author shimingming
 * @since 2023/4/3 15:11
 */
@Slf4j
@Component
public class Init implements ApplicationRunner {

    @Value("${service.version:'未定义'}")
    public String version;

    @Autowired
    private RedisTemplate redisTemplate;

    @Autowired
    private UploadService uploadService;

    @Resource
    private ImageLoader imageLoader;

    private final String picName = "default.png";

    @Autowired
    private RoomMapper roomMapper;

    @Autowired
    private RoomConfigMapper roomConfigMapper;

    @Override
    public void run(ApplicationArguments args) {


        // 资源文件初始化
        initGuoXinResourceFile();

        // 每次发版，日志自动开启7天
        startLog();

        // 表情开关config 设置
        syncGiftConfigFlag();

    }

    private void syncGiftConfigFlag() {

        LambdaQueryWrapper<RoomConfig> wrapperConfig = Wrappers.lambdaQuery();
        wrapperConfig.eq(RoomConfig::getConfigKey, RoomConfigStatusEnum.CHAT_MANAGEMENT_GIFT.getValue());
        List<RoomConfig> roomConfigs = roomConfigMapper.selectList(wrapperConfig);
        List<Integer> ilIdList = new ArrayList<>();
        if (CollectionUtil.isNotEmpty(roomConfigs)) {
            ilIdList = roomConfigs.stream().map(RoomConfig::getIlId).collect(Collectors.toList());
        }


        LambdaQueryWrapper<RoomsEntity> wrapper = Wrappers.lambdaQuery();
        wrapper.notIn(CollectionUtil.isNotEmpty(ilIdList), RoomsEntity::getIlId, ilIdList);
        List<RoomsEntity> roomsEntities = roomMapper.selectList(wrapper);

        if (CollectionUtil.isNotEmpty(roomsEntities)) {

            for (RoomsEntity roomsEntity : roomsEntities) {
                RoomConfig roomConfig = new RoomConfig();
                roomConfig.setRoomId(roomsEntity.getRoomId());
                roomConfig.setIlId(roomsEntity.getIlId());
                roomConfig.setAccountId(roomsEntity.getAccountId());
                roomConfig.setConfigKey(RoomConfigStatusEnum.CHAT_MANAGEMENT_GIFT.getValue());
                roomConfig.setConfigValue(RoomConfigStatusEnum.CHAT_MANAGEMENT_GIFT.getDefauleValue());
                roomConfig.setCreatedAt(LocalDateTime.now());
                roomConfig.setUpdatedAt(LocalDateTime.now());
                roomConfigMapper.insert(roomConfig);
            }
        }


    }

    private void startLog() {
        redisTemplate.opsForValue().set(RedisKey.PASS_LOG, "开启日志输出", 7, TimeUnit.DAYS);
        redisTemplate.opsForValue().set(RedisKey.PASS_LOG_TASK, "开启日志输出", 7, TimeUnit.DAYS);
        log.info("每次发版，日志自动开启7天");
    }

    private void initGuoXinResourceFile() {

        Object o = redisTemplate.opsForValue().get(RESOURCE_IMAGE_GX);

        if (o == null) {
            // 初始化，资源文件图片
            try {
//                byte[] fileContent = getFileContent();

                BufferedImage bufferedImage = imageLoader.loadImage(picName);
                byte[] fileContent = imageLoader.convertImageToByteArray(bufferedImage, "png");

                MultipartFile multipartFile =
                        new MockMultipartFile(picName, picName, "image/jpeg", fileContent);

                Map<String, String> result = uploadService.doUpload(multipartFile, "");

                String url = result.get("url");
                if (StringUtils.isNotBlank(url)) {
                    redisTemplate.opsForValue().set(RESOURCE_IMAGE_GX, url);
                    log.info(MessageFormat.format("初始化资源文件成功：【{0}】", url));
                }
            } catch (Exception e) {
                e.printStackTrace();
                log.error(MessageFormat.format("自动上传资源文件异常：【{0}】", e.getMessage()));
            }
        } else {
            log.info(MessageFormat.format("资源文件成功已经存在：【{0}】", o.toString()));
        }
    }


    private byte[] getFileContent() throws FileNotFoundException {
        File file = ResourceUtils.getFile("classpath:" + picName);
        byte[] fileContent = null;
        try {
            FileInputStream inputStream = new FileInputStream(file);
            ByteArrayOutputStream outputStream = new ByteArrayOutputStream();
            IOUtils.copy(inputStream, outputStream);
            fileContent = outputStream.toByteArray();
        } catch (IOException e) {
            // 处理异常
            log.error(MessageFormat.format("getFileContent 异常：【{0}】", e.getMessage()));
        }
        return fileContent;
    }
}
